<template>
    <div class="info-box">
        <div class="title">控制人信息</div>
        <el-form
            class="form-box"
            ref="formInfoRef"
            v-loading="loading"
            :element-loading-text="loadingText"
            :model="formInfo"
            :rules="rules"
            :inline="false"
            scroll-to-error
            :disabled="props.disabled"
            label-position="top"
            label-width="auto">
            <el-row>
                <el-col :span="24">
                    <el-form-item :label="`实际控制人是否为${labelText}`" prop="ctl_is_lp">
                        <el-radio-group v-model="formInfo.ctl_is_lp" @change="changeIsLp">
                            <el-radio :label="1" size="large">是</el-radio>
                            <el-radio :label="2" size="large">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <template v-if="formInfo.ctl_is_lp == 2">
                <!-- <el-row :gutter="30">
                    <el-col :span="8">
                        <el-form-item label="实际控制人类型" prop="ctl_type">
                            <el-select v-model="formInfo.ctl_type" placeholder="请选择实际控制人类型" clearable>
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row> -->
                <template v-if="formInfo.ctl_type == 1">
                    <el-row :gutter="60">
                        <el-col :span="8">
                            <el-form-item class="id-card-item" label="实际控制人身份证人像面" prop="ctl_id_card_front">
                                <div class="upload-img-box">
                                    <ZwUnityKitCertificateUpload
                                        v-model="formInfo.ctl_id_card_front"
                                        v-model:imageList="ctl_id_card_front_url"
                                        ocrType="RESIDENT_CARD_NATIONAL_HEAD"
                                        uploadLabel="上传身份证人像面"
                                        :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                        :multiple="false"
                                        :disabled="props.disabled"
                                        uploadTips=""
                                        validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M"
                                        @submit="getlpIdCardFront"
                                        @start="onStartLoading"
                                        @finished="onFinishedLoading" />
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item class="id-card-item" label="实际控制人身份证国徽面" prop="ctl_id_card_back">
                                <div class="upload-img-box">
                                    <ZwUnityKitCertificateUpload
                                        v-model="formInfo.ctl_id_card_back"
                                        v-model:imageList="ctl_id_card_back_url"
                                        ocrType="RESIDENT_CARD_NATIONAL_EMBLEM"
                                        uploadLabel="上传身份证国徽面"
                                        :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                        :multiple="false"
                                        :disabled="props.disabled"
                                        uploadTips=""
                                        validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M"
                                        @submit="getlpIdCardBack"
                                        @start="onStartLoading"
                                        @finished="onFinishedLoading" />
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="30">
                        <el-col :span="12">
                            <el-form-item label="" prop="name">
                                <div class="id-card-desc">
                                    上传身份证后自动识别信息。支持JPG、BMP、PNG格式，图片大小不能超过1M。
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="60">
                        <el-col :span="8">
                            <el-form-item label="实际控制人姓名" prop="ctl_name">
                                <el-input
                                    v-model.trim="formInfo.ctl_name"
                                    placeholder="请输入实际控制人姓名"
                                    type="text"
                                    maxlength="16"
                                    show-word-limit
                                    clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="身份证号码" prop="ctl_id_card">
                                <el-input
                                    v-model.trim="formInfo.ctl_id_card"
                                    placeholder="请输入身份证号码"
                                    type="text"
                                    maxlength="18"
                                    show-word-limit
                                    clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="身份证有效期限" prop="ctl_times">
                                <ZwUnityKitDatePicker
                                    v-model="formInfo.ctl_times"
                                    v-model:isLongTerm="formInfo.ctl_id_card_is_long"
                                    type="RESIDENT" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="60">
                        <el-col :span="8">
                            <el-form-item label="身份证归属地区" prop="ctl_id_card_area">
                                <ZwUnityKitCascader
                                    v-model="formInfo.ctl_id_card_area"
                                    clearable
                                    placeholder="请选择身份证归属地区" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="身份证地址" prop="ctl_id_card_address">
                                <el-input
                                    v-model.trim="formInfo.ctl_id_card_address"
                                    placeholder="请输入身份证地址"
                                    type="text"
                                    maxlength="64"
                                    show-word-limit
                                    clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </template>
                <template v-if="formInfo.ctl_type == 2">
                    <el-row :gutter="60">
                        <el-col :span="8">
                            <el-form-item label="实际控制企业营业执照图片" prop="ctl_corp_license">
                                <div class="upload-img-box">
                                    <ZwUnityKitCertificateUpload
                                        v-model="formInfo.ctl_corp_license"
                                        :imageList="formInfo.ctl_corp_license_url"
                                        :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                        :multiple="false"
                                        :disabled="props.disabled"
                                        ocrType="LICENSE"
                                        uploadLabel="上传营业执照"
                                        @submit="onUploadOCR"
                                        uploadTips="上传营业执照后自动识别信息。支持JPG、BMP、PNG格式，图片大小不能超过1M。"
                                        validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M" />
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="60">
                        <el-col :span="8">
                            <el-form-item label="实际控制企业姓名" prop="ctl_corp_name">
                                <el-input
                                    v-model.trim="formInfo.ctl_corp_name"
                                    placeholder="请输入实际控制企业姓名"
                                    type="text"
                                    maxlength="32"
                                    show-word-limit
                                    clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="统一社会信用代码" prop="ctl_corp_unified_social_credit_code">
                                <el-input
                                    v-model.trim="formInfo.ctl_corp_unified_social_credit_code"
                                    placeholder="请输入统一社会信用代码"
                                    type="text"
                                    maxlength="18"
                                    show-word-limit
                                    clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="营业期限" prop="ctl_corp_times">
                                <ZwUnityKitDatePicker
                                    v-model="formInfo.ctl_corp_times"
                                    v-model:isLongTerm="formInfo.ctl_corp_license_term_is_long" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </template>
            </template>
        </el-form>
    </div>
</template>
<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { packSelectObjUtil, getRegExp } from '@/commons/utils';
import constants from '@/commons/constants';

const formInfoRef = ref(null);
// 是否长期有效 1-是 2-否
const isLongTerm = ref(2);

const loading = ref(false);
const loadingText = ref('');

const emit = defineEmits(['update:modelValue']);

const props = defineProps({
    modelValue: {
        type: Object,
        default: () => {}
    },
    disabled: {
        type: Boolean,
        default: false
    },
    corpMainType: {
        type: [String, Number],
        default: 1
    }
});

const formInfo = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

const labelText = computed(() => {
    if (props.corpMainType == 1) {
        return '法人';
    }
    if (props.corpMainType == 2) {
        return '经营者';
    }
    return '';
});

const options = reactive(packSelectObjUtil(constants.ACTUAL_CONTROLLER_TYPE));

const ctl_id_card_front_url = ref({
    code: '',
    url: ''
});

const ctl_id_card_back_url = ref({
    code: '',
    url: ''
});

const checkTimes = (ruls, value = [], callback) => {
    if (!value[0] || !value[1]) {
        return callback(new Error('请选择身份证有效期限'));
    }
    if (new Date(value[0]).getTime() - new Date(value[1]).getTime() >= 0) {
        return callback(new Error('结束时间需要大于开始时间'));
    }
    if (new Date(value[1]).getTime() - new Date().getTime() < 60 * 24 * 60 * 60 * 1000) {
        return callback(new Error('结束时间距当前时间需超过60天'));
    }
    callback();
};

const rules = reactive({
    ctl_is_lp: [{ required: true, message: '请选择实际控制人是否为法人', trigger: 'change' }],
    ctl_type: [{ required: true, message: '请选择实际控制人类型', trigger: 'change' }],
    ctl_id_card_front: [{ required: true, message: '请上传身份证人像面', trigger: 'change' }],
    ctl_id_card_back: [{ required: true, message: '请上传身份证国徽面', trigger: 'change' }],
    ctl_name: [{ required: true, message: '请输入实际控制人姓名', trigger: 'blur' }],
    ctl_id_card: [
        { required: true, message: '请输入身份证号码', trigger: 'blur' },
        { pattern: getRegExp('idcard'), message: '身份证号码格式不正确', trigger: 'blur' }
    ],
    ctl_times: [{ required: true, validator: checkTimes, trigger: 'change' }],
    ctl_id_card_area: [{ required: true, message: '请选择身份证归属地区', trigger: 'change' }],
    ctl_id_card_address: [{ required: true, message: '请输入身份证地址', trigger: 'blur' }],
    ctl_corp_license: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
    ctl_corp_name: [{ required: true, message: '请输入实际控制企业姓名', trigger: 'blur' }],
    ctl_corp_times: [{ required: true, validator: checkTimes, trigger: 'change' }],
    ctl_corp_unified_social_credit_code: [
        { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
        { pattern: /^[0-9A-Z]{18}$/, message: '请输入正确的统一社会信用代码', trigger: 'blur' }
    ]
});

/**
 * 表单校验
 * @param {*} typeList 需要校验的字段，默认全校验
 */
const validate = async (typeList = []) => {
    if (typeList.length) {
        let errNum = 0;
        for (let i = 0; i < typeList?.length; i++) {
            try {
                await formInfoRef.value?.validateField(typeList[i]);
            } catch (err) {
                errNum++;
            }
        }
        return !errNum;
    } else {
        return await formInfoRef.value?.validate();
    }
};

/**
 * @description: 获取身份证人像面信息
 * @param {*} info
 * @return {*}
 */
const getlpIdCardFront = info => {
    formInfoRef.value?.clearValidate('ctl_id_card_front');
    if (info) {
        const { name: ctl_name, idNumber: ctl_id_card, address: ctl_id_card_address, area: ctl_id_card_area } = info;
        if (ctl_name && !formInfo.value.ctl_name) {
            formInfo.value.ctl_name = ctl_name;
            formInfoRef.value?.clearValidate('ctl_name');
        }
        if (ctl_id_card && !formInfo.value.ctl_id_card) {
            formInfo.value.ctl_id_card = ctl_id_card;
            formInfoRef.value?.clearValidate('ctl_id_card');
        }
        if (ctl_id_card_address && !formInfo.value.ctl_id_card_address) {
            formInfo.value.ctl_id_card_address = ctl_id_card_address;
            formInfoRef.value?.clearValidate('ctl_id_card_address');
        }
        if (ctl_id_card_area && !formInfo.value.ctl_id_card_area) {
            formInfo.value.ctl_id_card_area = ctl_id_card_area;
            formInfoRef.value?.clearValidate('ctl_id_card_area');
        }
    }
};

/**
 * @description: 获取身份证国徽面信息
 * @param {*} info
 * @return {*}
 */
const getlpIdCardBack = info => {
    formInfoRef.value?.clearValidate('ctl_id_card_back');
    if (info) {
        const { validPeriod } = info;
        if (validPeriod) {
            if (!formInfo.value.ctl_times || formInfo.value.ctl_times.filter(ite => ite).length < 2) {
                if (validPeriod.includes('长期')) {
                    formInfo.value.ctl_id_card_is_long = 1;
                    const ctl_times = validPeriod.split('-')[0].replace(/\./g, '-');
                    formInfo.value.ctl_times = [ctl_times];
                } else {
                    formInfo.value.ctl_id_card_is_long = 2;
                    const ctl_times = validPeriod.split('-').map(ite => ite.replace(/\./g, '-'));
                    formInfo.value.ctl_times = ctl_times;
                }
                formInfoRef.value?.clearValidate('ctl_times');
            }
        }
    }
};

const onUploadOCR = (val = {}) => {
    // console.log(val,'12333')
    formInfoRef.value?.clearValidate('ctl_corp_license');
    if (!formInfo.value.ctl_corp_name) {
        formInfo.value.ctl_corp_name = val.legalPerson;
        formInfoRef.value?.clearValidate('ctl_corp_name');
    }
    if (!formInfo.value.ctl_corp_unified_social_credit_code) {
        formInfo.value.ctl_corp_unified_social_credit_code = val.creditCode;
        formInfoRef.value?.clearValidate('ctl_corp_unified_social_credit_code');
    }
    if (
        !formInfo.value.ctl_corp_times.length ||
        (!formInfo.value.ctl_corp_times[0] && !formInfo.value.ctl_corp_times[1])
    ) {
        let list = val.validPeriod?.split('至') || [];
        if (list.length == 2) {
            let startTime = list[0].replace(/年|月/g, '-').replace(/日/g, '');
            let endTime = list[1].replace(/年|月/g, '-').replace(/日/g, '');
            formInfo.value.ctl_corp_times[0] = startTime;
            if (['不约定期限', '长期'].includes(list[1])) {
                formInfo.value.ctl_corp_license_term_is_long = 1;
            } else if (endTime) {
                formInfo.value.ctl_corp_times[1] = endTime;
            }
        }
    }
};

const onStartLoading = () => {
    loading.value = true;
    loadingText.value = '正在识别...';
};

const onFinishedLoading = () => {
    loading.value = false;
    loadingText.value = '';
};

/**
 * 实际控制人是否为法人
 * 否的时候，默认实际控制人类型为1-个人
 * @param {*} val
 */
const changeIsLp = val => {
    if (val == 2) {
        formInfo.value.ctl_type = 1;
    }
};

watch(
    () => formInfo.value?.ctl_id_card_front_url,
    val => {
        if (val) {
            ctl_id_card_front_url.value.code = formInfo.value.ctl_id_card_front;
            ctl_id_card_front_url.value.url = formInfo.value.ctl_id_card_front_url;
        }
    }
);

watch(
    () => formInfo.value?.ctl_id_card_back_url,
    val => {
        if (val) {
            ctl_id_card_back_url.value.code = formInfo.value.ctl_id_card_back;
            ctl_id_card_back_url.value.url = formInfo.value.ctl_id_card_back_url;
        }
    }
);

defineExpose({
    formInfoRef,
    validate
});
</script>
<style lang="scss" scoped>
.el-form-item {
    margin-bottom: 24px;
}
.info-box {
    margin-bottom: 16px;
    background: #ffffff;
    .title {
        padding: 16px 24px;
        font-size: 16px;
        font-weight: 500;
        color: #333333;
        line-height: 24px;
        border-bottom: 1px solid #e9e9e9;
    }
    .form-box {
        margin: 24px 24px 0;
        .label {
            span {
                font-size: 14px;
                color: rgba(153, 153, 153, 0.85);
                line-height: 22px;
            }
            .label-btn {
                padding-left: 16px;
                font-size: 14px;
                font-weight: 400;
                color: #ff6b00;
                line-height: 20px;
                cursor: pointer;
            }
        }
        .label-desc {
            padding-top: 8px;
            font-size: 12px;
            font-weight: 400;
            color: #999999;
            line-height: 17px;
        }
        .upload-img-box {
            width: 45%;
        }
        .id-card-item {
            margin-bottom: 0px;
            :deep(.el-form-item__error) {
                padding-top: 28px;
            }
        }
        .id-card-desc {
            padding-top: 8px;
            font-size: 12px;
            font-weight: 400;
            color: #999999;
            line-height: 17px;
        }
    }
}
</style>
